import React, { useState, useEffect, useCallback } from 'react';
import { ConfigProvider, Button, Card } from 'antd-mobile';
import zhCN from 'antd-mobile/es/locales/zh-CN';
import './game.less';
import { GameLevel, useGameData } from '@/hooks/useGameData';
import { HistoryOutlined, StarOutlined, udp } from '@cscec/udp-mobile-ui';
import CloseOutline from 'antd-mobile-icons/es/CloseOutline';
import UndoOutline from 'antd-mobile-icons/es/UndoOutline';
import RightOutline from 'antd-mobile-icons/es/RightOutline';
import PlayOutline from 'antd-mobile-icons/es/PlayOutline';
import RiseOutlined from '@ant-design/icons/lib/icons/RiseOutlined';
import FieldTimeOutlined from '@ant-design/icons/lib/icons/FieldTimeOutlined';
import GameControllerIconAlternative from '@/components/GameControllerIconAlternative';
import BellaHeader from '@/components/header';
import audioPlayer from '../../utils/audioPlayer';
import { message } from 'antd';

// 游戏状态类型
type GameState = 'start' | 'playing' | 'levelComplete' | 'gameOver' | 'allComplete';

// 卡片类型
interface CardType {
  id: string;
  type: 'word' | 'image';
  content: string;
  matchId: string;
  alt?: string;
  matched: boolean;
}

const App: React.FC = () => {
  // 使用自定义Hook获取游戏数据
  const { gameData, loading, error, refreshData } = useGameData();
  
  // 游戏状态
  const [gameState, setGameState] = useState<GameState>('start');
  const [currentLevel, setCurrentLevel] = useState(0);
  const [cards, setCards] = useState<CardType[]>([]);
  const [selectedCard, setSelectedCard] = useState<CardType | null>(null);
  const [timer, setTimer] = useState<NodeJS.Timeout | null>(null);
  
  // 游戏统计数据
  const [stats, setStats] = useState({
    totalScore: 0,
    currentLevelScore: 0,
    currentLevelMaxScore: 0,
    timeLeft: 60,
    matchedPairs: 0,
    totalPairs: 0,
    attempts: 0,
    correctAttempts: 0,
    totalTimeUsed: 0,
    totalAttempts: 0,
    totalCorrectAttempts: 0,
  });

  // 计算总最高分数
  const totalMaxScore = gameData.reduce((sum, level) => sum + level.length * 2, 0);

  // 生成混合卡片
  const generateMixedCards = useCallback((levelData: GameLevel[]) => {
    const allCards: CardType[] = [];
    
    levelData.forEach(item => {
      // 单词卡片
      allCards.push({
        id: `${item.word}-word`,
        type: 'word',
        content: item.word,
        matchId: `${item.word}-image`,
        alt: item?.alt,
        matched: false,
      });
      
      // 图片卡片
      allCards.push({
        id: `${item.word}-image`,
        type: 'image',
        content: item.image,
        matchId: `${item.word}-word`,
        alt: item?.alt,
        matched: false,
      });
    });
    
    // 随机打乱卡片顺序
    const shuffledCards = allCards.sort(() => Math.random() - 0.5);
    setCards(shuffledCards);
  }, []);

  // 开始游戏
  const startGame = () => {
    if (gameData.length === 0) return;
    
    setGameState('playing');
    setCurrentLevel(0);
    setStats(prev => ({
      ...prev,
      totalScore: 0,
      totalTimeUsed: 0,
      totalAttempts: 0,
      totalCorrectAttempts: 0,
    }));
    loadLevel(0);
  };

  // 加载关卡
  const loadLevel = (levelIndex: number) => {
    if (timer) clearInterval(timer);
    
    const levelData = gameData[levelIndex];
    const levelMaxScore = levelData.length * 2;
    // const timeLeft = 60 + (levelIndex * 10);
    const timeLeft = 60;
    
    setStats(prev => ({
      ...prev,
      currentLevelScore: 0,
      currentLevelMaxScore: levelMaxScore,
      timeLeft,
      matchedPairs: 0,
      totalPairs: levelData.length,
      attempts: 0,
      correctAttempts: 0,
    }));
    
    setSelectedCard(null);
    generateMixedCards(levelData);
    startTimer();
  };

  // 启动计时器
  const startTimer = () => {
    if (timer) clearInterval(timer);
    
    const newTimer = setInterval(() => {
      setStats(prev => {
        if (prev.timeLeft <= 1) {
          clearInterval(newTimer);
          gameOver();
          return { ...prev, timeLeft: 0 };
        }
        return { ...prev, timeLeft: prev.timeLeft - 1 };
      });
    }, 1000);
    
    setTimer(newTimer);
  };

  // 选择卡片
  const selectCard = (card: CardType) => {
    if (card.matched || gameState !== 'playing') return;
    
    // 情况1：已有选中卡片
    if (selectedCard) {
      // 子情况1.1：点击的是已选中的卡片（取消选中）
      if (card.id === selectedCard.id) {
        setSelectedCard(null);
        return;
      }
      
      // 子情况1.2：点击的是同类型卡片（取消之前选中，选中新卡片）
      if (card.type === selectedCard.type) {
        setSelectedCard(card);
        return;
      }
      
      // 子情况1.3：点击的是不同类型卡片（判断是否匹配）
      setStats(prev => ({ 
        ...prev, 
        attempts: prev.attempts + 1, 
        totalAttempts: prev.totalAttempts + 1 
      }));
      
      if (card.matchId === selectedCard.id) {
          audioPlayer.playCorrect();
        // 匹配成功
        setStats(prev => ({
          ...prev,
          correctAttempts: prev.correctAttempts + 1,
          totalCorrectAttempts: prev.totalCorrectAttempts + 1,
          matchedPairs: prev.matchedPairs + 1,
          currentLevelScore: prev.currentLevelScore + 2,
          totalScore: prev.totalScore + 2,
        }));
        
        // 标记卡片为已匹配
        setCards(prev => prev.map(c => 
          c.id === card.id || c.id === selectedCard.id 
            ? { ...c, matched: true }
            : c
        ));
        
        // 显示成功效果
        setTimeout(() => {
          setSelectedCard(null);
          //setHintVisible(false);
          
          // 检查是否完成所有匹配
          setStats(prev => {
            if (prev.matchedPairs === prev.totalPairs) {
              completeLevel();
            }
            return prev;
          });
        }, 600);
        
      } else {
        audioPlayer.playWrong();
        console.log('播放错误音效')
        // 匹配失败：扣1分
        setStats(prev => ({
          ...prev,
          currentLevelScore: Math.max(prev.currentLevelScore - 1, 0),
          totalScore: Math.max(prev.totalScore - 1, 0),
        }));
        
        // 显示错误效果
        setTimeout(() => {
          setSelectedCard(null);
        }, 800);
      }
    } 
    // 情况2：无选中卡片（直接选中当前卡片）
    else {
      setSelectedCard(card);
    }
  };

  // 完成关卡
  const completeLevel = () => {
    if (timer) clearInterval(timer);
    
    const levelTime = 60 + (currentLevel * 10) - stats.timeLeft;
    setStats(prev => ({
      ...prev,
      totalTimeUsed: prev.totalTimeUsed + levelTime,
    }));
    
    setGameState('levelComplete');
    
    // 检查是否是最后一关
    if (currentLevel === gameData.length - 1) {
      setTimeout(() => {
        setGameState('allComplete');
      }, 1500);
    }
  };

  // 游戏结束
  const gameOver = () => {
    setGameState('gameOver');
  };

  // 下一关
  const goToNextLevel = () => {
    const nextLevel = currentLevel + 1;
    if (nextLevel < gameData.length) {
      setCurrentLevel(nextLevel);
      //setSelectedText('')
      loadLevel(nextLevel);
      setGameState('playing');
    } else {
      setGameState('allComplete');
    }
  };

  // 重新开始
  const restartGame = () => {
    if (timer) clearInterval(timer);
    refreshData()
    setGameState('start');
  };

  // 计算正确率
  const calculateAccuracy = (attempts: number, correct: number) => {
    return attempts > 0 ? Math.round((correct / attempts) * 100) : 0;
  };

  // 清理计时器
  useEffect(() => {
    return () => {
      if (timer) clearInterval(timer);
    };
  }, [timer]);

  // 显示加载状态
  if (loading) {
    return (
      <ConfigProvider locale={zhCN}>
        <div className="min-h-screen flex items-center justify-center">
          <div className="text-center">
            <div className="text-2xl text-primary mb-4">加载中...</div>
            <div className="text-darkText">正在获取游戏数据</div>
          </div>
        </div>
      </ConfigProvider>
    );
  }

  // 显示错误状态
  if (error) {
    return (
      <ConfigProvider locale={zhCN}>
        <div className="min-h-screen flex items-center justify-center">
          <div className="text-center">
            <div className="text-2xl text-error mb-4">加载失败</div>
            <div className="text-darkText mb-4">{error}</div>
            <Button color="primary" onClick={refreshData}>
              重新加载
            </Button>
          </div>
        </div>
      </ConfigProvider>
    );
  }

  return (
    <ConfigProvider locale={zhCN}>
      <div className="min-h-screen bg-light">
         {/* 头部 */}
       {gameState === 'playing'?"": <BellaHeader />}
        {/* 装饰元素 */}
        <div className="fixed top-5 left-10 w-8 h-8 bg-kb1 rounded-full decor floating"></div>
        <div className="fixed top-20 right-8 w-6 h-6 bg-kb2 rounded-full decor floating" style={{animationDelay: '0.5s'}}></div>
        <div className="fixed top-40 left-1-4 w-7 h-7 bg-kb3 rounded-full decor floating" style={{animationDelay: '1s'}}></div>
        <div className="fixed bottom-10 right-10 w-9 h-9 bg-kb4 rounded-full decor floating" style={{animationDelay: '0.3s'}}></div>

        <div className="container mx-auto px-4 py-6 relative z-10">
          {/* 开始界面 */}
          {gameState === 'start' && (
            <div className="block">
              <div className="text-center mt-10 mb-8">
                <div className="w-24 h-24 bg-secondary1 rounded-full mx-auto flex items-center justify-center mb-4 floating">
                  <i className="fa fa-gamepad text-game text-3xl"><GameControllerIconAlternative
                  size={50}
                  /></i>
                </div>
                <h1 className="text-3xl font-bold text-primary text-shadow mb-2">Word Elimination Game</h1>
                <p className="text-darkText text-lg">Find the words and their corresponding pictures!</p>
                <p className="text-darkText-80 text-sm mt-1">Total of <span className="text-primary font-bold">{gameData.length}</span> levels</p>
                <p className="text-darkText-80 text-sm">The score for each level is calculated based on the number of words</p>
              </div>
              
              <Button 
                color="primary" 
                size="large"
                className="block mx-auto bg-game text-white py-4 px-12 rounded-full shadow-xl text-lg font-bold pulse-game"
                onClick={startGame}
              >
                <i className="fa fa-play mr-2"><PlayOutline /></i>Start Game
              </Button>
            </div>
          )}
          
          {/* 游戏界面 */}
          {gameState === 'playing' && (
            <div className="block">
              {/* 游戏信息栏 */}
              <div className="bg-white rounded-xl shadow-md p-3 mb-4 flex justify-between items-center">
                <div className="flex items-center">
                  <div className="w-10 h-10 bg-secondary1 rounded-full flex items-center justify-center mr-2">
                    <RiseOutlined className="text-primary" style={{
                      fontSize:"1.25rem",
                      fontStyle:'normal'
                    }}/>
                  </div>
                  <span className="font-bold text-darkText"><span className="text-primary">{currentLevel + 1}</span>/{gameData.length}</span>
                </div>
                
                <div className="flex items-center">
                  <div className="w-10 h-10 bg-secondary1 rounded-full flex items-center justify-center mr-2">
                    <i style={{
                      color:"yellow",
                      fontSize:"1.25rem",
                      fontStyle:'normal'
                    }}>★</i>
                  </div>
                  <span className="font-bold text-darkText"><span className="text-primary">{stats.currentLevelScore}</span>/{stats.currentLevelMaxScore}</span>
                </div>
                
                <div className="flex items-center">
                  <div className="w-10 h-10 bg-secondary1 rounded-full flex items-center justify-center mr-2">
                    <FieldTimeOutlined style={{
                      color:"red",
                      fontSize:"1.25rem"
                    }}/>
                  </div>
                  <span className={`font-bold text-darkText ${stats.timeLeft <= 10 ? 'animate-pulse text-error' : ''}`}>
                    <span className={stats.timeLeft <= 10 ? 'text-error' : 'text-primary'}>{stats.timeLeft}</span>
                  </span>
                </div>
              {/* 退出按钮 */}
              <Button 
                size="small"
                color="danger"
                onClick={()=>{
                  udp.close()
                }}
                className="bg-error text-white py-1 px-3 rounded-lg font-bold shadow-md hover:opacity-90 transition-opacity"
              >
                <i className="fa fa-sign-out mr-1"><CloseOutline /></i>Exit
              </Button>
              </div>
              
              {/* 游戏卡片区域 */}
              <div className="game-container" 
              //style={{padding:"0px"}}
              >
                <div className="grid grid-cols-3 gap-3">
                  {cards.map((card, index) => (
                    <div
                      key={card.id}
                      className={`
                        bg-white rounded-xl shadow-md overflow-hidden card-bounce scale-in cursor-pointer square-card
                        ${selectedCard?.id === card.id ? 'card-selected' : ''}
                        ${card.matched ? 'card-matched' : ''}
                      `}
                      style={{ animationDelay: `${index * 0.05}s`,
                        marginTop:'1.5rem'
                      }}
                      onClick={() => selectCard(card)}
                    >
                      {card.type === 'word' ? (
                        <div className="flex-1 flex items-center justify-center p-2">
                          <span className="text-xl font-bold text-primary" style={{
                            textAlign:'center'
                          }} >{card.content}</span>
                        </div>
                      ) : (
                        <div className="flex-1 overflow-hidden">
                          <img src={card.content} alt={card.alt} className="w-full h-full object-cover" />
                        </div>
                      )}
                    </div>
                  ))}
                </div>
              </div>
            </div>
          )}
          
          {/* 关卡完成界面 */}
          {gameState === 'levelComplete' && (
            <div className="text-center">
              <div className="mt-12 mb-6">
                <div className="w-32 h-32 bg-kb2 rounded-full mx-auto flex items-center justify-center floating">
                  <i className="fa fa-trophy text-kb3 text-5xl" style={{
                    fontStyle:"normal"
                  }}>🏆</i>
                </div>
                <h2 className="text-2xl font-bold text-primary mt-4">Great！</h2>
                <p className="text-darkText text-lg mt-2">
                  level <span className="text-primary font-bold">{currentLevel + 1}</span>/
                  <span className="text-primary font-bold">{gameData.length}</span> Completed!
                </p>
              </div>
              
              <div className="bg-white rounded-2xl p-6 shadow-lg max-w-md mx-auto mb-8">
                <div className="flex justify-between items-center mb-6">
                  <span className="text-darkText text-lg">Score for this level</span>
                  <div className="bg-secondary2 px-4 py-2 rounded-full">
                    <span className="text-primary font-bold text-2xl">{stats.currentLevelScore}</span>
                    <span className="text-darkText-70 font-bold text-xl">/{stats.currentLevelMaxScore}</span>
                  </div>
                </div>
                
                <div className="flex justify-between items-center mb-4">
                  <span className="text-darkText">Time Spent</span>
                  <span className="text-primary font-bold text-xl">{60 + (currentLevel * 10) - stats.timeLeft}s</span>
                </div>
                
                <div className="flex justify-between items-center">
                  <span className="text-darkText">Accuracy Rate</span>
                  <span className="text-primary font-bold text-xl">{calculateAccuracy(stats.attempts, stats.correctAttempts)}%</span>
                </div>
              </div>
              
              {currentLevel < gameData.length - 1 && (
                <div style={{display:'flex'}}>
                <Button 
                  color="primary" 
                  className="block mx-auto bg-primary text-white py-3 px-10 rounded-full shadow-lg text-lg font-bold"
                  onClick={goToNextLevel}
                  style={{
                    fontSize:"14px"
                  }}
                >
                  <i className="fa fa-arrow-right mr-2"><RightOutline /></i>Next Level
                </Button>
                  {/* <Button 
                  className="block mx-auto bg-primary text-white py-3 px-10 rounded-full shadow-lg text-lg font-bold"
                  style={{backgroundColor:'red',fontSize:"14px",marginLeft:"10px"}}
                  onClick={()=>{udp.close()}}
                >
                  <i className="fa fa-arrow-right mr-2"><CloseOutline /></i>Quit Game
                </Button> */}
                </div>
              )}
            </div>
          )}
          
          {/* 游戏结束界面 */}
          {gameState === 'gameOver' && (
            <div className="text-center">
              <div className="mt-12 mb-6">
                <div className="w-28 h-28 bg-error rounded-full mx-auto flex items-center justify-center bg-opacity-20">
                  <i className="fa fa-clock-o text-error text-4xl" style={{
                    color:'#fff',
                    fontStyle:'normal'
                  }} ><HistoryOutlined/></i>
                </div>
                <h2 className="text-2xl font-bold text-error mt-4">Time's up!</h2>
                <p className="text-darkText text-lg mt-2">
                   <span className="text-primary font-bold">{currentLevel + 1}</span>/
                  <span className="text-primary font-bold">{gameData.length}</span>of the levels completed
                </p>
              </div>
              
              <div className="bg-white rounded-2xl p-6 shadow-lg max-w-md mx-auto mb-8">
                <div className="flex justify-between items-center mb-4">
                  <span className="text-darkText">Your score</span>
                  <span className="text-primary font-bold text-xl">{stats.totalScore}</span>
                </div>
                <div className="flex justify-between items-center">
                  <span className="text-darkText">Accuracy Rate</span>
                  <span className="text-primary font-bold text-xl">{calculateAccuracy(stats.totalAttempts, stats.totalCorrectAttempts)}%</span>
                </div>
              </div>
              <div style={{display:'flex'}}>
                  <Button 
                    color="primary" 
                    className="block mx-auto bg-game text-white py-3 px-10 rounded-full shadow-lg text-lg font-bold pulse-game"
                    onClick={restartGame}
                    style={{
                    fontSize:"14px"
                  }}
                  >
                    <i className="fa fa-refresh mr-2"><UndoOutline /></i>Do it again
                  </Button>
                  {/* <Button 
                    className="block mx-auto bg-game text-white py-3 px-10 rounded-full shadow-lg text-lg font-bold pulse-game"
                    style={{backgroundColor:'red',fontSize:"14px",marginLeft:"10px"}}
                    onClick={()=>{udp.close()}}
                  >
                    <i className="fa fa-refresh mr-2"><CloseOutline /></i>Quit Game
                  </Button> */}
              </div>
            </div>
          )}
          
          {/* 全部关卡完成界面 */}
          {gameState === 'allComplete' && (
            <div className="text-center">
              <div className="mt-12 mb-6">
                <div className="w-36 h-36 bg-kb3 rounded-full mx-auto flex items-center justify-center floating">
                  <i className="fa fa-trophy text-kb3 text-6xl" style={{
                    fontStyle:"normal"
                  }}>🏆</i>
                </div>
                <h2 className="text-3xl font-bold text-primary mt-4"> Great!</h2>
                <p className="text-darkText text-lg mt-2">You have successfully completed all levels!</p>
              </div>
              
              <div className="bg-white rounded-2xl p-6 shadow-lg max-w-md mx-auto mb-8">
                <div className="flex justify-between items-center mb-4">
                  <span className="text-darkText">Total Score</span>
                  <div>
                    <span className="text-primary font-bold text-2xl">{stats.totalScore}</span>
                    <span className="text-darkText-70 font-bold text-xl">/{totalMaxScore}</span>
                  </div>
                </div>
                
                <div className="flex justify-between items-center mb-4">
                  <span className="text-darkText">Total Time</span>
                  <span className="text-primary font-bold text-xl">{stats.totalTimeUsed}s</span>
                </div>
                
                <div className="flex justify-between items-center">
                  <span className="text-darkText">Average accuracy</span>
                  <span className="text-primary font-bold text-xl">{calculateAccuracy(stats.totalAttempts, stats.totalCorrectAttempts)}%</span>
                </div>
              </div>
              {/* <div style={{display:'flex'}}> */}
              <Button 
                color="primary" 
                className="block mx-auto bg-game text-white py-3 px-10 rounded-full shadow-lg text-lg font-bold pulse-game"
                onClick={restartGame}
                style={{
                    fontSize:"14px"
                }}
              >
                <i className="fa fa-refresh mr-2"><UndoOutline /></i>Do it again
              </Button>
              {/* <Button 
                className="block mx-auto bg-game text-white py-3 px-10 rounded-full shadow-lg text-lg font-bold pulse-game"
                style={{backgroundColor:'red',fontSize:"14px",marginLeft:"10px"}}
                onClick={()=>{udp.close()}}
              >
                <i className="fa fa-refresh mr-2"><CloseOutline /></i>Quit Game
              </Button> */}
              {/* </div> */}
            </div>
          )}
        </div>
      </div>
    </ConfigProvider>
  );
};

export default App;